package com.springboot.nacos.config;

import com.springboot.nacos.config.refresh.NacosContextRefresher;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.SearchStrategy;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration(proxyBeanMethods = false)
@ConditionalOnProperty(name = {"small.nacos.config.enabled"}, matchIfMissing = true)
public class NacosConfigAutoConfiguration {

    /**
     * 如果bootStrap中有配置,这里将会取bootStrap中的配置，如果application中有相同配置，将会覆盖掉bootStrap中的配置
     *
     * @param context
     * @return
     */
    @Bean
    @ConditionalOnMissingBean(value = NacosConfigProperties.class, search = SearchStrategy.CURRENT)
    public NacosConfigProperties nacosConfigProperties(ApplicationContext context) {
        if (context.getParent() != null
                && BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
                context.getParent(), NacosConfigProperties.class).length > 0) {
            return BeanFactoryUtils.beanOfTypeIncludingAncestors(context.getParent(),
                    NacosConfigProperties.class);
        }
        return new NacosConfigProperties();
    }

    @Bean
    public NacosConfigManager nacosConfigManager(
            NacosConfigProperties nacosConfigProperties) {
        return new NacosConfigManager(nacosConfigProperties);
    }

    @Bean
    public NacosContextRefresher nacosContextRefresher(
            NacosConfigManager nacosConfigManager) {
        return new NacosContextRefresher(nacosConfigManager);
    }
}
